package model;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class WeatherDataAverager {
	private final String SOURCE_FILE_NAME = "/res/sources.txt";
	private final String CITIES_FILE_NAME = "/res/cities.txt";

	public void generateReport() {
		try{
			ArrayList<City> availableCities = getCityNames();
			for (City city : availableCities) {
				double cityTemperature =findMeanTemperature(city);
				System.out.println("City "+ city.getName() + " has mean temperature of "+ cityTemperature + " degrees");
				
			}
	
		} catch (Exception e) {
			// TODO: handle exception
			
		}
	}

	private double findMeanTemperature(City city) throws IOException {
		int counter = 0;
		double sumOfTemperatures =0;
		for (WeatherSource weatherSource : getWeatherSources()){
			sumOfTemperatures += weatherSource.getTempForCity(city.getName());
			counter++;
		}
		
		double meanTemperature =sumOfTemperatures / counter;
		
		return meanTemperature;
		
		

	}

	private ArrayList<City> getCityNames() throws IOException {
		ArrayList<City> availableCities = new ArrayList<City>();
		FileReader fr = new FileReader(CITIES_FILE_NAME);
		BufferedReader br = new BufferedReader(fr);
		String s;
		while ((s = br.readLine()) != null) {
			City thisCity = new City(s);
			System.out.println("New City found with name: " + s);
			availableCities.add(thisCity);
			
		}
		fr.close();

		return availableCities;
	}

	private ArrayList<WeatherSource> getWeatherSources() throws IOException {
		ArrayList<WeatherSource> availableSources= new ArrayList<WeatherSource>();
		FileReader fr = new FileReader(SOURCE_FILE_NAME);
		BufferedReader br = new BufferedReader(fr);
		String s;
		while ((s = br.readLine()) != null) {
			String[] seperatedValues =s.split(",");
			WeatherSource thisSource = new WeatherSource(seperatedValues[0], seperatedValues[1]);
			System.out.println("New Weather Source found with name: " + thisSource.getSourceName());
			availableSources.add(thisSource);
		}
		fr.close();
		
		return availableSources;
	}
	
	
}
